#!/usr/bin/python -u
# Michael P. Reilly (C) 2013-2015 All rights reserved
# Installation program for sshcmd, including man pages

import base64
import os
import subprocess
import sys

RelNo = '$RelNo$'
_revision_num = '$Revision$'

def decodefile(filename, string):
    from base64 import b64decode
    open(filename, 'w').write(b64decode(string))

def main(instdir):
    assert [f for f in code if not code[f].startswith('$')] and\
           [f for f in doc if not doc[f].startswith('$')] and\
           [f for f in comp if not comp[f].startswith('$')], \
        'Program not initialized.\nPlease run "pyerect" in the build directory.'

    if not os.path.isdir(instdir):
        os.mkdir(instdir)
    bindir = os.path.join(instdir, 'bin')
    if not os.path.isdir(bindir):
        os.mkdir(bindir)
    for fn in code:
        filename = os.path.join(bindir, fn)
        decodefile(filename, code[fn])
        os.chmod(filename, 0755)
    if not os.path.islink(os.path.join(bindir, 'sshcpy')):
        os.symlink('sshcmd', os.path.join(bindir, 'sshcpy'))

    if os.path.isdir(os.path.join(instdir, 'share')):
        mandir = os.path.join(instdir, 'share', 'man')
    else:
        mandir = os.path.join(instdir, 'man')
    man1dir = os.path.join(mandir, 'man1')
    man5dir = os.path.join(mandir, 'man5')
    if not os.path.isdir(mandir):
       os.mkdir(mandir)
    if not os.path.isdir(man1dir):
        os.mkdir(man1dir)
    if not os.path.isdir(man5dir):
        os.mkdir(man5dir)
    for fn in doc:
        if fn.endswith('.1'):
            filename = os.path.join(man1dir, fn)
        elif fn.endswith('.5'):
            filename = os.path.join(man5dir, fn)
        decodefile(filename, doc[fn])
        subprocess.call(['gzip', '-qf', filename])
    if not os.path.islink(os.path.join(man1dir, 'sshcpy.1.gz')):
        os.symlink('sshcmd.1.gz', os.path.join(man1dir, 'sshcpy.1.gz'))
    compdir = os.path.join(instdir, '.bash')
    if not os.path.isdir(compdir):
        os.mkdir(compdir)
    if comp:
        print '# bash completion scripts'
        for fn in comp:
            filename = os.path.join(compdir, fn)
            decodefile(filename, comp[fn])
            os.chmod(filename, 0755)
            print 'source', filename
    print '# add the following to your .profile or .bash_profile'
    print 'export MANPATH="%s:`manpath -g`"' % mandir

code = {
    'sshcmd': '$sshcmd_code$',
    'svrfilter': '$svrfilter_code$',
}
doc = {
    'sshcmd.1': '$sshcmd_doc$',
    'svrfilter.1': '$svrfilter_doc$',
    'svrfilter.5': '$server_doc$',
}
comp ={
    'sshcmd.comp': '$sshcmd_comp$',
    'svrfilter.comp': '$svrfilter_comp$',
}

if __name__ == '__main__':
    instdir = os.path.normpath(os.path.expanduser('~'))
    if len(sys.argv) > 1:
        if sys.argv[1] in ('--help', '-h'):
            print sys.argv[0], '[instdir]'
            raise SystemExit
        instdir = os.path.abspath(os.path.normpath(sys.argv[1]))
    main(instdir)
